using Catalog.Application.Brands.Commands;
using Catalog.Application.Brands.Interfaces;
using Catalog.Application.Interfaces;
using MediatR;

namespace Catalog.Application.Brands.CommandHandlers;

public class UpdateBrandCommandHandler : IRequestHandler<UpdateBrandCommand, Unit>
{
    private readonly IBrandRepository _brandRepository;
    private readonly IUnitOfWork _unitOfWork;
    public UpdateBrandCommandHandler(IBrandRepository brandRepository, IUnitOfWork unitOfWork)
    {
        _brandRepository = brandRepository;
        _unitOfWork = unitOfWork;

    }
    public async Task<Unit> Handle(UpdateBrandCommand request, CancellationToken cancellationToken)
    {
        var brand = await _brandRepository.GetByIdAsync(request.id);
        if (brand == null)
            throw new KeyNotFoundException("品牌不存在");

        brand.ChangeName(request.newName);
        brand.ChangeDescription(request.newDescription);
        await _unitOfWork.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}